package com.study.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {

    private static final String SING = "!DJFONRGOEWH324gdt&&&87uj!@%%$&#Jmm";


    //生成Token header.payload.signature

    public static String getToken(Map<String,String> paramsMap){

        Map<String,Object> map = new HashMap<>();
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,7);//默认7天过期

        JWTCreator.Builder builder = JWT.create();
        paramsMap.forEach(((k,v)->{
            builder.withClaim(k,v);
        }));

        String token = builder.withExpiresAt(instance.getTime())
                              .sign(Algorithm.HMAC256(SING));


        System.out.println(token);

        return token;
    }


    //验证token合法性
    public static void verify(String token){

        JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }

    //获取token信息
    public static DecodedJWT getTokenInfo(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
        return verify;
    }
}
